import datetime

from django.shortcuts import render

from djhousehold.settings import BASE_DIR
from order.models import OrderModel0, OrderModel1, OrderModel2,OrderGoodsModel0,OrderGoodsModel1,OrderGoodsModel2
from recommend.models import GoodsModel
from rest_framework.views import APIView
from rest_framework.response import Response
import os
from tools.baiduapi import CheckText

# Create your views here.


class RateGoodsView(APIView):
    def get(self,request):
        order_id = request.query_params.get('order_id')
        user_id = int(request.query_params.get('user_id'))
        table_id = hash(user_id) % 3
        order_goods_model = [OrderGoodsModel0, OrderGoodsModel1, OrderGoodsModel2][table_id]
        goods_data = order_goods_model.objects.filter(order_id=order_id)
        data = []
        for i in goods_data:
            data.append({
                'goods_id': i.goods_id,
                'goods_name': i.goods.name,
            })
        return Response(data)


class GoodsRateView(APIView):
    def post(self,request):
        user_id = request.data['user_id']
        goods_id = request.data['goods_id']
        rate_text = request.data['rate_text']
        test_result = CheckText.main(rate_text)
        if test_result != True:
            return Response("您的评价中含有敏感词")




        file = request.data.get('file')
        if file:
            date_year = str(datetime.datetime.now().year)
            date_month = str(datetime.datetime.now().month)
            date_day = str(datetime.datetime.now().day)
            file_name = file.name
            dir_path = os.path.join(BASE_DIR,'media','upload',date_year,date_month,date_day)
            if not os.path.exists(dir_path):
                os.makedirs(dir_path)
            with open(os.path.join(dir_path,file_name),'wb') as f:
                for chunk in file.chunks():
                    f.write(chunk)

            file_data = f'http://127.0.0.1:8000/media/upload/{date_year}/{date_month}/{date_day}/{file_name}'



        return Response("ok")




